/**
 * This file is part of magnolia-module-bespin.
 * 
 * magnolia-module-bespin is free software: you
 * can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * magnolia-module-bespin is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public
 * License for more details.
 * 
 * You should have received a copy of the GNU General
 * Public License along with magnolia-module-bespin.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

package com.nrgedge.magnolia.module.bespin;

import info.magnolia.cms.gui.dialog.DialogBox;
import info.magnolia.cms.gui.misc.CssConstants;

import java.io.IOException;
import java.io.Writer;

import javax.jcr.PropertyType;

/**
 * Based off of info.magnolia.cms.gui.dialog.DialogEditCode
 * 
 * @author brian.bowman@nrg-edge.com
 * @author adam.galloway@nrg-edge.com
 */
public class DialogEditCodeBespin extends DialogBox {
	/**
	 * @see info.magnolia.cms.gui.dialog.DialogControl#drawHtml(Writer)
	 */
	public void drawHtml(Writer out) throws IOException {
		BespinEdit control = new BespinEdit(this.getName(), this.getValue());
		
		control.setType(this.getConfigValue("type", PropertyType.TYPENAME_STRING));
		if (this.getConfigValue("saveInfo").equals("false")) {
			control.setSaveInfo(false);
		}
		control.setCssClass(CssConstants.CSSCLASS_EDIT + " bespin ");
		
		out.write("<script type=\"text/javascript\" src=\"" 
			+ this.getRequest().getContextPath()
			+ "/.resources/bespin/BespinEmbedded.js\"></script>");
		out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\""
			+ this.getRequest().getContextPath()
			+ "/.resources/bespin/BespinEmbedded.compressed.css\"/>");
		out.write(control.getHtml());
		out.write("\n<script>\n");
		out.write("MgnlDHTMLUtil.addOnLoad(function(){\n");
		out.write("    var b = document.getElementById('mgnlSaveButton');\n");
		out.write("    var existingOnClick = b.onclick;\n");
		out.write("    b.onclick=function(){\n");
		out.write("        document.getElementById('cp_hidden_"
			+ this.getName() + "').value = document.getElementById('"
			+ this.getName() + "').bespin.value;\n");
		out.write("        existingOnClick.apply(this);\n");
		out.write("    }\n});\n");
		out.write("</script>\n");
		out.write("<input type=\"hidden\" name=\"");
		out.write(this.getName());
		out.write("\" id=\"cp_hidden_" + this.getName() + "\" />\n");

		this.drawHtmlPost(out);
	}
}